package cn.edu.njnu.opengmpback.common.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hpsf.extractor.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@Slf4j
public class previewUtils {

    public static String previewTxtFile(String filePath) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
        return content;
    }

    public static String previewCsvFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        CSVParser parser = CSVParser.parse(Files.newBufferedReader(path, StandardCharsets.UTF_8), CSVFormat.DEFAULT);
        StringBuilder preview = new StringBuilder();
        for (CSVRecord record : parser) {
            preview.append(String.join(", ", record)).append("\n");
        }
        return preview.toString().length() > 1000 ? preview.substring(0, 1000) + "..." : preview.toString();
    }

    public static String previewJsonFile(String filePath) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Object json = mapper.readValue(Paths.get(filePath).toFile(), Object.class);
        String prettyJson =  mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
        return prettyJson.length() > 1000 ? prettyJson.substring(0, 1000) + "..." : prettyJson;
    }

    public static String previewExcelFile(String filePath) throws IOException {
        Workbook workbook = WorkbookFactory.create(Paths.get(filePath).toFile());
        StringBuilder preview = new StringBuilder();
        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            for (Cell cell : row) {
                preview.append(cell.toString()).append("\t");
            }
            preview.append("\n");
        }
        return preview.toString().length() > 1000 ? preview.substring(0, 1000) + "..." : preview.toString();
    }

    public static String previewDocFile(String filePath) throws IOException {
        StringBuilder preview = new StringBuilder();

        if (filePath.toLowerCase().endsWith(".docx")) {
            try (XWPFDocument docx = new XWPFDocument(new FileInputStream(Paths.get(filePath).toFile()))) {
                docx.getParagraphs().forEach(paragraph -> {
                    preview.append(paragraph.getText()).append("\n");
                });
            }
        } else if (filePath.toLowerCase().endsWith(".doc")) {
            try (FileInputStream fis = new FileInputStream(filePath);
                 HWPFDocument doc = new HWPFDocument(fis);
                 WordExtractor extractor = new WordExtractor(doc)) {
                String[] paragraphs = extractor.getParagraphText();
                for (String paragraph : paragraphs) {
                    preview.append(paragraph).append("\n");
                }
            }
        } else {
            throw new IllegalArgumentException("Unsupported file format: " + filePath);
        }

        return preview.toString().length() > 1000 ? preview.substring(0, 1000) + "..." : preview.toString();
    }
}
